from rest_framework.views import APIView
from app.account.models import UserInfo, UserPassword, UserLog, UserSetting
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
import json


class RegisterInfoView(APIView):

    def post(self, request):
        """
        注册账户
        :param request:
        :return:
        """
        params = request.body
        jsonParams = json.loads(params.decode('utf-8'))
        # 检查参数合法性
        if jsonParams.get('email') is None or jsonParams.get('nickname') is None or jsonParams.get('password') is None:
            return JsonResponse({
                'status': False,
                'errMsg': '有空字段，请完成填写'
            }, status=401)
        user = UserInfo.objects.filter(email__exact=jsonParams.get('email'))
        if user.exists():
            return JsonResponse({
                'status': False,
                'errMsg': '邮箱已经被注册'
            }, status=401)
        user = UserInfo.objects.filter(nickname__exact=jsonParams.get('nickname'))
        if user.exists():
            return JsonResponse({
                'status': False,
                'errMsg': '昵称已经被人抢先用啦'
            }, status=401)
        del user
        # 密码转码
        hash_password = make_password(jsonParams.get('password'))
        newPassword = UserPassword.objects.create(password=hash_password)
        newUser = UserInfo.objects.create(
            password=newPassword,
            email=jsonParams.get('email'),
            nickname=jsonParams.get('nickname'),
        )
        UserLog.objects.create(related_user=newUser)
        UserSetting.objects.create(related_user=newUser)
        return JsonResponse({
            'status': True,
            'email': newUser.email,
            'id': newUser.id,
            'nickname': newUser.nickname
        })
